export interface Message {
    name: string;
    data: any;
}

export class MessageClient {
    private listeners: { [name: string]: ((data: any) => void)[] } = {};
    private port2: MessagePort | null = null;

    private serverWindow: Window | null = null;
    constructor() {
        this.serverWindow = globalThis.window;
        if (!this.serverWindow) {
            throw new Error('无法获取主窗口');
        }
        window.addEventListener('message', this.handlePortMessage.bind(this), false);

        this.serverWindow.postMessage('CONNECT');
    }

    /**
     * 注册消息接收的处理函数
     * @param name - 消息名称
     * @param callback - 消息处理函数
     */
    public onMessage(name: string, callback: (data: any) => void) {
        if (!this.listeners[name]) {
            this.listeners[name] = [];
        }
        this.listeners[name].push(callback);
    }

    // 发送消息给服务端
    public sendMessage(name: string, data: any) {
        if (!this.port2) {
            console.error('Port not established.');
            return;
        }
        console.log('client send message', name, data);
        this.port2.postMessage({ name: name, data: data });
    }

    private handlePortMessage(event: MessageEvent) {
        if (event.data.type === 'PORT') {
            console.log('client handle');
            this.port2 = event.ports[0];

            // 监听消息
            this.port2.addEventListener('message', this.receiveMessage.bind(this));
            this.port2.start();
        }
    }
    
    /**
     * 接收消息并调用已注册的处理函数
     * @param event - 传递的事件对象
     */
    private receiveMessage(event: MessageEvent) {
        console.log('Server received message:', event.data);
        const message: Message = event.data;
        if (this.listeners[message.name]) {
            this.listeners[message.name].forEach((callback) => callback(message.data));
        }
    }
}
